package com.xiaodu.acer.phoneplay.di.module;

import android.app.Application;

import com.google.gson.Gson;
import com.xiaodu.acer.phoneplay.common.http.CommonParamsInterceptor;
import com.xiaodu.acer.phoneplay.common.rx.RxErrorHandler;
import com.xiaodu.acer.phoneplay.data.http.ApiService;

import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author 小杜 QQ:1392229149
 * @name phone
 * @class name：com.xiaodu.acer.phoneplay.d2.moudle
 * @class describe
 * @time 2017/12/16 21:26
 * @change
 * @chang time
 * @class describe
 */
@Module
public class HttpModule {

    @Provides
    @Singleton
    public OkHttpClient provideOkHttpClient(Application application, Gson gson) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        if (BuildConfig.DEBUG) {
//            // log用拦截器
//            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
//
//            // 开发模式记录整个body，否则只记录基本信息如返回200，http协议版本等
//            logging.setLevel( HttpLoggingInterceptor.Level.BODY );
//            builder.addNetworkInterceptor( logging );
//
//        }
        // 如果使用到HTTPS，我们需要创建SSLSocketFactory，并设置到client
        //        SSLSocketFactory sslSocketFactory = null;

        return builder
                .addInterceptor( new CommonParamsInterceptor( application, gson ) )
                // 连接超时时间设置
                .connectTimeout( 10, TimeUnit.SECONDS )
                // 读取超时时间设置
                .readTimeout( 10, TimeUnit.SECONDS )
                .build();


    }


    @Provides
    @Singleton
    public Retrofit provideRetrofit(OkHttpClient okHttpClient) {

        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl( ApiService.BASE_URL )
                .addConverterFactory( GsonConverterFactory.create() )
                .addCallAdapterFactory( RxJava2CallAdapterFactory.create() )
                .client( okHttpClient );


        return builder.build();

    }


    @Provides
    @Singleton
    public ApiService provideApiService(Retrofit retrofit) {
        return retrofit.create( ApiService.class );
    }


    @Provides
    @Singleton
    public RxErrorHandler provideErrorHandlder(Application application) {
        return new RxErrorHandler( application );
    }


}

